namespace GameToolkit.BehaviourTree
{

    [System.Serializable]
    [CompositeTitle("执行序列", Description = "Sequence")]
    [CompositeCategory]
    [CompositeIcon("baad7c299c663c946908f82e6a925719")]
    [JsonImporter(FormerlySerializedAs = "BTSequence")]
    public class Sequence : ExecutableComposite
    {
        public override BehaviourTreeObject Create()
        {
            return new Impl();
        }

        class Impl : ControllerNode
        {
            int mNextIndex;
            protected override void OnCreate(BehaviourTreePlayer player)
            {
            }

            protected override void OnDestroy(BehaviourTreePlayer player)
            {
            }

            protected override NodeState GetNextBehaviour(BehaviourTreePlayer player, out ExecutableEntry nextNode)
            {
                var prev = mNextIndex - 1;
                if (prev >= 0 && GetChild(prev).State == NodeState.Failed)
                {
                    nextNode = null;
                    return NodeState.Failed;
                }
                if (mNextIndex < ChildCount)
                {
                    nextNode = GetChild(mNextIndex++);
                    return NodeState.Running;
                }
                else
                {
                    nextNode = null;
                    return NodeState.Success;
                }
            }

            protected override void OnStart(BehaviourTreePlayer player)
            {
                mNextIndex = 0;
            }

            protected override void OnStop(BehaviourTreePlayer player)
            {
            }
        }
    }

}
